﻿using IRepositoryBll;
using IRepositoryDal;
using RepositoryEntity;
using RepositoryEntity.DTO;
using RepositoryEntity.ResultModel.MenuInfoResultModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RepositoryBll
{
    public class MenuInfoBll : IMenuInfoBll
    {
        private IMenuInfoDal _menuInfoDal;
        private IR_UserInfo_MenuInfoDal _r_UserInfo_MenuInfoDal;
        private IR_UserInfo_RoleInfoDal _r_UserInfo_RoleInfoDal;
        private IRoleInfoDal _roleInfoDal;
        public MenuInfoBll(IMenuInfoDal menuInfoDal, IR_UserInfo_MenuInfoDal r_UserInfo_MenuInfoDal, IR_UserInfo_RoleInfoDal r_UserInfo_RoleInfoDal, IRoleInfoDal roleInfoDal)
        {
            _menuInfoDal = menuInfoDal;
            _r_UserInfo_MenuInfoDal = r_UserInfo_MenuInfoDal;
            _r_UserInfo_RoleInfoDal = r_UserInfo_RoleInfoDal;
            _roleInfoDal = roleInfoDal;

        }
        public bool AddMenuInfo(MenuInfo menuInfo)
        {
            return _menuInfoDal.Add(menuInfo);
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="menuInfoId"></param>
        /// <returns></returns>
        public bool DeleteRoleInfo(string menuInfoId)
        {
            return _menuInfoDal.Delete(menuInfoId);
        }


        /// <summary>
        /// 获取菜单集合
        /// </summary>
        /// <returns></returns>
        public List<MenuInfoResultModel> GetInitMenus(UserInfo userInfo)
        {
            
            int count = (from ur in _r_UserInfo_RoleInfoDal.GetEntitiesDb().Where(r => r.UserInfoID == userInfo.ID)
                         join r in _roleInfoDal.GetEntitiesDb().Where(r => !r.IsDelete && r.RoleName == "系统管理员")
                         on ur.RoleInfoID equals r.ID
                         select ur.ID).Count();

            //三目判断运算
            bool isHas = count > 0 ? true : false;

            List<MenuInfoDTO> menus = new List<MenuInfoDTO>();
            if (userInfo.IsAdmin == true && isHas == true)
            {
                //获取菜单集合
                 menus = _menuInfoDal.GetEntitiesDb().Where(m => !m.IsDelete).OrderBy(m => m.Sort).Select(m => new MenuInfoDTO
                {
                    ID = m.ID,

                    Title = m.Title,
                    Icon = m.Icon,
                    Href = m.Href,
                    Target = m.Target,
                    Level = m.Level,
                    ParentId = m.ParentId
                }).ToList();
            }
            else
            {
                //用户ID获取用户角色
                var roleInfoIds = _r_UserInfo_RoleInfoDal.GetEntitiesDb().Where(u => u.UserInfoID == userInfo.ID).Select(u => u.RoleInfoID).ToList(); 
                //获取菜单ID集合
                var menuIds = _r_UserInfo_MenuInfoDal.GetEntitiesDb().Where(r => roleInfoIds.Contains(r.RoleId)).Select(r => r.MenuId).ToList();


                //去重后的菜单id
                var dMenuIds = menuIds.Distinct().ToList();

                menus = (from m in _menuInfoDal.GetEntitiesDb().Where(m => menuIds.Contains(m.ID)).ToList()
                         join menuId in dMenuIds
                         on m.ID equals menuId
                         select new
                         {
                             ID = m.ID,
                             m.Sort,
                             Title = m.Title,
                             Icon = m.Icon,
                             Href = m.Href,
                             Target = m.Target,
                             Level = m.Level,
                             ParentId = m.ParentId
                         }).OrderBy(m => m.Sort).Select(m => new MenuInfoDTO
                         {
                             ID = m.ID,
                             Title = m.Title,
                             Icon = m.Icon,
                             Href = m.Href,
                             Target = m.Target,
                             Level = m.Level,
                             ParentId = m.ParentId
                         }).ToList();





                //menus = (from rm in _r_UserInfo_MenuInfoDal.GetEntitiesDb().Where(r => roleInfoIds.Contains(r.RoleId))
                //            join m in _menuInfoDal.GetEntitiesDb().Where(m => !m.IsDelete)
                //            on rm.MenuId equals m.ID
                //            select new
                //            {
                //                ID = m.ID,
                //                m.Sort,
                //                Title = m.Title,
                //                Icon = m.Icon,
                //                Href = m.Href,
                //                Target = m.Target,
                //                Level = m.Level,
                //                ParentId = m.ParentId
                //            }).OrderBy(m => m.Sort).Select(m => new MenuInfoDTO
                //            {
                //                ID = m.ID,
                //                Title = m.Title,
                //                Icon = m.Icon,
                //                Href = m.Href,
                //                Target = m.Target,
                //                Level = m.Level,
                //                ParentId = m.ParentId
                //            }).ToList();
            }



            //获取菜单集合
            //var menus = _menuInfoDal.GetEntitiesDb().Where(m => !m.IsDelete).OrderBy(m => m.Sort).Select(m => new MenuInfoDTO
            //{
            //    ID = m.ID,

            //    Title = m.Title,
            //    Icon = m.Icon,
            //    Href = m.Href,
            //    Target = m.Target,
            //    Level = m.Level,
            //    ParentId = m.ParentId
            //}).ToList();

            //获取父级菜单集合
            List<MenuInfoResultModel> paretMenus = menus.Where(m => m.Level == 0 && m.ParentId == null).Select(m => new MenuInfoResultModel
            {
                ID = m.ID,
                href = m.Href,
                icon = m.Icon,
                target = m.Target,
                title = m.Title
            }).ToList();

            foreach (var paretMenu in paretMenus)
            {
                //查询父级自身的菜单(即父级菜单自身的子菜单，每个子菜单皆可为其他子菜单的父级)
                var childMenus = menus.Where(m => m.ParentId == paretMenu.ID).Select(m => new MenuInfoResultModel
                {
                    ID = m.ID,
                    href = m.Href,
                    icon = m.Icon,
                    target = m.Target,
                    title = m.Title
                }).ToList();
                //为父级菜单添加子菜单
                paretMenu.child = childMenus;
                //调取父级菜单赋值给子菜单
                RecursionMenu(paretMenu.child, menus);
            }
            return paretMenus;
        }
        /// <summary>
        /// 赋值菜单集合（递归）
        /// </summary>
        /// <param name="pMenus"></param>
        /// <param name="menus"></param>
        public void RecursionMenu(List<MenuInfoResultModel> pMenus, List<MenuInfoDTO> menus)
        {
            foreach (var item in pMenus)
            {
                var childMenus2 = menus.Where(m => m.ParentId == item.ID).Select(m => new MenuInfoResultModel
                {
                    ID = m.ID,
                    href = m.Href,
                    icon = m.Icon,
                    target = m.Target,
                    title = m.Title
                }).ToList();
                //为父级菜单添加子菜单
                item.child = childMenus2;

                RecursionMenu(item.child, menus);

            }
        }

        /// <summary>
        /// ID获取菜单
        /// </summary>
        /// <param name="menuInfoId"></param>
        /// <returns></returns>
        public MenuInfo GetMenuInfo(string menuInfoId)
        {
            return _menuInfoDal.GetEntity(menuInfoId);
        }

        public object GetMenuInfoListByPage(int page, int limit, out int count, string title)
        {
            //获取菜单数据
            var menuInfo = _menuInfoDal.GetEntitiesDb().Where((u => u.IsDelete == false));
            if (!string.IsNullOrEmpty(title))
            {
                menuInfo = menuInfo.Where(u => u.Title.Contains(title));
            }

            var tempMenuList = from m in menuInfo
                               join m2 in _menuInfoDal.GetEntitiesDb()
                               on m.ParentId equals m2.ID into mmTemp
                               from m3 in mmTemp.DefaultIfEmpty()
                               select new
                               {
                                   m.ID,
                                   m.Description,
                                   m.Level,
                                   m.Sort,
                                   m.Href,
                                   m.Icon,
                                   m.Title,
                                   m.Target,
                                   ParetTilte = m3.Title,
                                   m.CreateTime
                               };
            //统计数据数量
            count = menuInfo.Count();
            var list = tempMenuList.OrderBy(r => r.Sort).Skip((page - 1) * limit).Take(limit).ToList().Select(u =>
                  {
                      return new
                      {
                          u.ID,
                          u.Description,
                          u.Level,
                          u.Sort,
                          u.Href,
                          u.Icon,
                          u.Title,
                          u.Target,
                          u.ParetTilte,
                          CreateTime = u.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")

                      };

                  });


            return list;
        }
        /// <summary>
        /// 获取父级菜单集合
        /// </summary>
        /// <returns></returns>
        public object GetMenuSelectOption()
        {
            object menuInfoOptions = _menuInfoDal.GetEntitiesDb().Where(d => !d.IsDelete).Select(d => new
            {
                d.ID,
                d.Title
            }).ToList();
            return menuInfoOptions;
        }
        public object GetMenuSelectOption(string menuInfoId)
        {
            object menuInfoOptions = _menuInfoDal.GetEntitiesDb().Where(d => d.ID != menuInfoId && !d.IsDelete).Select(d => new
            {
                d.ID,
                d.Title
            }).ToList();
            return menuInfoOptions;
        }



        public List<MenuInfo> GetMenuInfoList()
        {
            return _menuInfoDal.GetEntitiesDb().Where(u => u.IsDelete == false).ToList();
        }

        public bool SoftDeleteMenuInfo(string menuInfoId)
        {
            MenuInfo menuInfo = _menuInfoDal.GetEntity(menuInfoId);
            if (menuInfo != null)
            {
                menuInfo.IsDelete = true;
                menuInfo.DeleteTime = DateTime.Now;
                return _menuInfoDal.Update(menuInfo);
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 更新修改页面数据信息
        /// </summary>
        /// <param name="menuInfoId"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="href"></param>
        /// <param name="icon"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public bool UpdateMenuInfo(string menuInfoId, string title, string description, int level, int sort, string href, string parentId, string icon, string target)
        {
            MenuInfo menuInfo = _menuInfoDal.GetEntity(menuInfoId);
            if (menuInfoId != null)
            {
                menuInfo.Title = title;
                menuInfo.Description = description;
                menuInfo.Level = level;
                menuInfo.Sort = sort;
                menuInfo.Href = href;
                menuInfo.ParentId = parentId;
                menuInfo.Icon = icon;
                menuInfo.Target = target;
                return _menuInfoDal.Update(menuInfo);
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 更新修改页面
        /// </summary>
        /// <param name="menuInfo"></param>
        /// <returns></returns>
        public bool UpdateMenuInfo(MenuInfo menuInfo)
        {
            return _menuInfoDal.Update(menuInfo);
        }


        /// <summary>
        /// 判断菜单是否相同
        /// </summary>
        /// <param name="title"></param>
        /// <returns></returns>
        public bool IsHadMenuInfo(string title)
        {
            int count = _menuInfoDal.GetEntitiesDb().Where(r => r.Title == title && !r.IsDelete).Count();
            return count > 0;
        }
        /// <summary>
        /// 获取菜单备选数据
        /// </summary>
        /// <returns></returns>
        public object GetSelectOption()
        {
            //linq
            var menuInfo = _menuInfoDal.GetEntitiesDb().Where(d => !d.IsDelete).OrderBy(d => d.Sort).Select(d => new
            {
                d.ID,
                d.Title
            }).ToList();
            return menuInfo;
        }
    }
}
